<template>
  <view class="app-container">
    <view class="history-container">
      <!-- 顶部工具栏 -->
      <view class="toolbar">
        <view class="toolbar-left">
          <button class="back-btn" @click="goBack">
            <uni-icons type="arrow-left" size="18" color="#5f6368"></uni-icons>
            <text>返回</text>
          </button>
        </view>
        
        <view class="toolbar-right">
          <view class="date-filter">
            <text>开始日期：</text>
            <input
              type="date"
              class="date-picker"
              v-model="startDate"
            />
            
            <text>结束日期：</text>
            <input
              type="date"
              class="date-picker"
              v-model="endDate"
            />
            
            <button class="btn btn-primary search-btn" @click="filterTasks">
              <uni-icons type="search" size="18" color="#ffffff"></uni-icons>
              <text class="search-btn-text">查询</text>
            </button>
          </view>
        </view>
      </view>
      
      <!-- 任务列表 -->
      <view class="task-list" id="taskList">
        <!-- 初始加载状态 -->
        <view v-if="isInitialLoading" class="loading-state">
          <uni-icons type="spinner-cycle" size="40" color="#1a73e8" class="loading-icon"></uni-icons>
          <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 空状态 -->
        <view v-else-if="tasks.length === 0" class="empty-state">
          <uni-icons type="inbox" size="60" color="#e0e0e0"></uni-icons>
          <text class="empty-title">暂无历史记录</text>
          <text class="empty-desc">您还没有拍摄过照片</text>
        </view>
        
        <!-- 任务卡片列表 -->
        <view v-else class="task-list-content">
          <view class="task-card" v-for="(task, index) in tasks" :key="task._id">
            <view class="task-header">
              <view class="task-title">任务 #{{task._id}}</view>
              <view class="task-time">{{new Date(task.create_date).toLocaleString()}}</view>
            </view>
            
            <view class="task-content">
              <!-- 原始照片 -->
              <view class="photos-section">
                <view class="section-title">原始照片</view>
                <view class="photos-grid">
                  <view 
                    class="photo-item original-photo" 
                    v-for="(photo, photoIndex) in task.photos" 
                    :key="photoIndex"
                    @click="previewPhoto({
                      photo_url: photo.photo_url,
                      original_url: photo.original_url || photo.photo_url,
                      type: 'original',
                      index: photo.index,
                      task: task
                    })"
                  >
                    <view class="photo-number">{{photo.index}}</view>
                    <image :src="photo.photo_url" mode="aspectFill"></image>
                  </view>
                </view>
              </view>
              
              <!-- 合成照片和GIF -->
              <view class="photos-section">
                <view class="section-title">合成效果</view>
                <view class="photos-grid">
                  <view 
                    class="photo-item template-photo"
                    v-for="(result, resultIndex) in task.result_images"
                    :key="resultIndex"
                    @click="previewPhoto({
                      image_url: result.thumbnail_url || result.image_url,
                      original_url: result.original_url || result.image_url,
                      type: 'composite',
                      task: task
                    })"
                  >
                    <image :src="result.thumbnail_url || result.image_url" mode="aspectFill"></image>
                  </view>
                  
                  <view 
                    class="photo-item gif-photo" 
                    v-if="task.gif_url"
                    @click="previewPhoto({
                      image_url: task.gif_thumbnail_url || task.gif_url,
                      original_url: task.gif_url,
                      type: 'gif',
                      task: task
                    })"
                  >
                    <image :src="task.gif_thumbnail_url || task.gif_url" mode="aspectFill"></image>
                  </view>
                </view>
              </view>
              
              <!-- 任务操作 -->
              <view class="task-actions">
                <button 
                  class="task-action-btn print-btn" 
                  @click="handlePrint(task.result_images[0])"
                  v-if="task.result_images && task.result_images.length > 0"
                >
                  <uni-icons type="paperplane" size="16" color="#ffffff"></uni-icons>
                  <text>打印</text>
                </button>
                
                <button class="task-action-btn delete-btn" @click="showDeleteConfirm(task)">
                  <uni-icons type="trash" size="16" color="#ffffff"></uni-icons>
                  <text>删除任务</text>
                </button>
              </view>
            </view>
          </view>
          
          <!-- 加载更多状态 -->
          <view v-if="hasMoreTasks" class="load-more-status">
            <text v-if="isLoadingMore" class="loading-text">
              <uni-icons type="spinner-cycle" size="18" color="#1a73e8" class="loading-icon mr-2"></uni-icons>
              加载更多...
            </text>
            <text v-else class="load-more-text">上拉加载更多</text>
          </view>
          <view v-else class="load-more-status">
            <text class="no-more-text">没有更多数据了</text>
          </view>
        </view>
      </view>
    </view>
  </view>

  <!-- 删除确认模态框 -->
  <uni-popup ref="deleteConfirmPopup" type="dialog">
    <uni-popup-dialog
      title="确认删除"
      content="确定要删除此任务及其所有照片吗？此操作无法撤销。"
      :before-close="true"
      @confirm="confirmDelete"
      @close="cancelDelete"
    ></uni-popup-dialog>
  </uni-popup>

  <!-- 打印进度模态框 -->
  <uni-popup ref="printProgressPopup" type="center" background-color="rgba(0,0,0,0.5)" :mask-click="false">
    <view class="modal-container">
      <view class="modal-header">
        <view class="modal-title">打印中</view>
      </view>
      <view class="modal-body">
        <view class="print-icon-container">
          <uni-icons type="paperplane" size="60" color="#1a73e8" class="print-icon"></uni-icons>
        </view>
        <view class="text-center text-gray-600 mb-4">正在打印照片，请稍候...</view>
        <view class="progress-bar-container">
          <view class="progress-bar" :style="{width: printProgress + '%'}"></view>
        </view>
        <view class="text-center text-gray-500">{{printStatus}}</view>
      </view>
    </view>
  </uni-popup>

  <!-- 图片预览弹窗 -->
  <uni-popup ref="photoPreviewPopup" type="center" background-color="rgba(0,0,0,0.85)" @change="e => e.show === false && closePhotoPreview()">
    <view class="photo-preview-modal">
      <view class="preview-close" @click="closePhotoPreview">
        <uni-icons type="close" size="24" color="#ffffff"></uni-icons>
      </view>
      <view class="preview-content">
        <image 
          class="preview-image" 
          :class="{'loaded': previewImageLoaded}" 
          :src="previewImageUrl" 
          mode="aspectFit"
          @load="onPreviewImageLoad"
        ></image>
      </view>
      <view class="preview-footer">
        <view class="preview-info">
          <text class="preview-title">{{previewPhotoInfo}}</text>
          <text class="preview-time">{{previewPhotoTime}}</text>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
import uniPopupDialog from '@/uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue'

const db = uniCloud.database()

// 添加日志函数
function log(action, message, data = {}) {
  console.log(`[History Page] ${action}:`, message, data);
  // 这里可以添加其他日志记录逻辑，比如发送到服务器等
}

export default {
  components: {
    uniIcons,
    uniPopup,
    uniPopupDialog
  },
  data() {
    return {
      tasks: [],
      currentTask: null,
      startDate: this.getDefaultStartDate(),
      endDate: this.getDefaultEndDate(),
      isLoading: false,
      isInitialLoading: true,
      isLoadingMore: false,
      hasMoreTasks: true,
      page: 1,
      pageSize: 10,
      // 预览相关
      previewImageUrl: '',
      previewPhotoInfo: '',
      previewPhotoTime: '',
      // 打印相关
      currentPrintPhoto: null,
      printCount: 1,
      printProgress: 0,
      printStatus: '',
      printInterval: null,
      // 缓存相关
      cacheKey: 'history_cache',
      cacheTimeout: 5 * 60 * 1000, // 5分钟缓存过期
      lastUpdateTime: 0,
      previewImageLoaded: false
    }
  },
  onLoad() {
    log('Page Load', '历史页面加载');
    this.loadTasks();
  },
  onPullDownRefresh() {
    log('Pull Refresh', '下拉刷新');
    this.page = 1;
    this.hasMoreTasks = true;
    this.loadTasks(true).then(() => {
      uni.stopPullDownRefresh();
    });
  },
  onReachBottom() {
    log('Reach Bottom', '触发上拉加载');
    if (this.hasMoreTasks && !this.isLoadingMore) {
      this.loadMore();
    }
  },
  methods: {
    getDefaultStartDate() {
      const date = new Date();
      date.setDate(date.getDate() - 30); // 默认30天前
      return this.formatDateForInput(date);
    },
    getDefaultEndDate() {
      return this.formatDateForInput(new Date());
    },
    formatDateForInput(date) {
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    // 缓存相关方法
    getCacheKey() {
      return `${this.cacheKey}_${this.startDate}_${this.endDate}`;
    },
    
    // 压缩任务数据，只保留必要字段
    compressTaskData(tasks) {
      return tasks.map(task => ({
        _id: task._id,
        create_date: task.create_date,
        photos: task.photos.map(photo => ({
          index: photo.index,
          photo_url: photo.photo_url
        })),
        result_images: task.result_images.map(img => ({
          image_url: img.image_url
        })),
        gif_url: task.gif_url
      }));
    },
    
    // 清理过期缓存
    clearExpiredCaches() {
      try {
        const keys = Object.keys(localStorage);
        const now = Date.now();
        
        keys.forEach(key => {
          if (key.startsWith(this.cacheKey)) {
            try {
              const data = JSON.parse(localStorage.getItem(key));
              if (now - data.timestamp > this.cacheTimeout) {
                localStorage.removeItem(key);
                log('Cache Cleanup', '清理过期缓存', { key });
              }
            } catch (e) {
              localStorage.removeItem(key);
            }
          }
        });
      } catch (error) {
        console.error('清理缓存失败:', error);
      }
    },
    
    // 检查并确保缓存空间充足
    ensureCacheSpace() {
      try {
        // 如果可用空间不足，按时间顺序清理旧缓存
        const keys = Object.keys(localStorage)
          .filter(key => key.startsWith(this.cacheKey))
          .map(key => {
            try {
              const data = JSON.parse(localStorage.getItem(key));
              return { key, timestamp: data.timestamp };
            } catch (e) {
              return { key, timestamp: 0 };
            }
          })
          .sort((a, b) => b.timestamp - a.timestamp);
        
        // 保留最近10个缓存，删除其他的
        if (keys.length > 10) {
          keys.slice(10).forEach(item => {
            localStorage.removeItem(item.key);
            log('Cache Cleanup', '清理旧缓存', { key: item.key });
          });
        }
      } catch (error) {
        console.error('清理缓存空间失败:', error);
      }
    },
    
    saveToCache(data) {
      try {
        // 清理过期和多余的缓存
        this.clearExpiredCaches();
        this.ensureCacheSpace();
        
        // 压缩数据
        const compressedTasks = this.compressTaskData(data);
        
        const cacheData = {
          tasks: compressedTasks,
          timestamp: Date.now(),
          startDate: this.startDate,
          endDate: this.endDate,
          page: this.page
        };
        
        // 尝试存储压缩后的数据
        try {
          localStorage.setItem(this.getCacheKey(), JSON.stringify(cacheData));
          this.lastUpdateTime = Date.now();
          log('Cache Save', '保存数据到缓存', { 
            cacheKey: this.getCacheKey(),
            dataSize: JSON.stringify(cacheData).length
          });
        } catch (storageError) {
          // 如果还是失败，清理所有相关缓存后重试一次
          log('Cache Save Retry', '存储失败，尝试清理所有缓存后重试');
          this.clearAllRelatedCaches();
          localStorage.setItem(this.getCacheKey(), JSON.stringify(cacheData));
        }
      } catch (error) {
        console.error('保存缓存失败:', error);
        // 缓存失败不影响正常功能
      }
    },
    
    clearAllRelatedCaches() {
      try {
        const keys = Object.keys(localStorage);
        keys.forEach(key => {
          if (key.startsWith(this.cacheKey)) {
            localStorage.removeItem(key);
          }
        });
        log('Cache Clear All', '清理所有相关缓存');
      } catch (error) {
        console.error('清理所有缓存失败:', error);
      }
    },
    
    getFromCache() {
      try {
        const cacheData = localStorage.getItem(this.getCacheKey());
        if (!cacheData) return null;
        
        const data = JSON.parse(cacheData);
        const now = Date.now();
        
        // 检查缓存是否过期
        if (now - data.timestamp > this.cacheTimeout) {
          localStorage.removeItem(this.getCacheKey());
          return null;
        }
        
        log('Cache Hit', '从缓存读取数据', { 
          cacheKey: this.getCacheKey(),
          dataSize: cacheData.length
        });
        return data;
      } catch (error) {
        console.error('读取缓存失败:', error);
        return null;
      }
    },
    
    // 修改加载任务方法，添加缓存支持
    async loadTasks(isPullRefresh = false) {
      if (this.isLoading) return;
      
      if (!isPullRefresh) {
        this.isLoading = true;
      }
      
      // 强制刷新或下拉刷新时，清除缓存
      if (isPullRefresh) {
        this.clearAllRelatedCaches();
      }
      
      // 尝试从缓存加载数据
      if (this.page === 1 && !isPullRefresh) {
        const cachedData = this.getFromCache();
        if (cachedData) {
          this.tasks = cachedData.tasks;
          this.page = cachedData.page;
          this.isLoading = false;
          this.isInitialLoading = false;
          this.isLoadingMore = false;
          return;
        }
      }
      
      log('Load Tasks', '开始加载任务列表', {
        page: this.page,
        pageSize: this.pageSize,
        startDate: this.startDate,
        endDate: this.endDate,
        isPullRefresh
      });
      
      try {
        // 构建查询条件
        const startTime = new Date(this.startDate).getTime();
        const endTime = new Date(this.endDate).getTime() + 24 * 60 * 60 * 1000 - 1;
        
        const where = {
          create_date: {
            $gte: startTime,
            $lte: endTime
          }
        };

        // 如果有最后更新时间，只获取新数据
        if (this.lastUpdateTime && !isPullRefresh) {
          where.create_date.$gt = this.lastUpdateTime;
        }

        log('Query Conditions', '查询条件', { where });

        // 查询总数
        const { result } = await db.collection('a-tasks')
          .where(where)
          .count();

        const total = result.total;
        log('Total Count', '查询总数', { total });
        
        // 查询数据
        const { result: queryResult } = await db.collection('a-tasks')
          .where(where)
          .skip((this.page - 1) * this.pageSize)
          .limit(this.pageSize)
          .orderBy('create_date', 'desc')
          .get();

        const tasks = queryResult.data;
        log('Tasks Loaded', '任务加载成功', {
          totalCount: total,
          loadedCount: tasks.length,
          currentPage: this.page
        });

        // 更新数据
        if (this.page === 1) {
          this.tasks = tasks;
          // 保存到缓存
          this.saveToCache(tasks);
        } else {
          // 合并新数据，避免重复
          const newTasks = [...this.tasks];
          tasks.forEach(task => {
            if (!newTasks.find(t => t._id === task._id)) {
              newTasks.push(task);
            }
          });
          this.tasks = newTasks;
          // 更新缓存
          this.saveToCache(newTasks);
        }

        // 判断是否还有更多数据
        this.hasMoreTasks = this.tasks.length < total;

      } catch (error) {
        log('Load Tasks Error', '加载任务失败', { error: error.message });
        console.error('加载任务失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        this.isInitialLoading = false;
        this.isLoadingMore = false;
      }
    },
    getMockTasks() {
      // 返回模拟数据
      return [
        {
          id: '1001',
          time: '2024-03-04 15:30',
          photos: [
            { id: 1, url: '/static/mock/photo1.jpg' },
            { id: 2, url: '/static/mock/photo2.jpg' },
            { id: 3, url: '/static/mock/photo3.jpg' }
          ],
          composite: '/static/mock/composite1.jpg',
          gif: '/static/mock/gif1.gif'
        },
        {
          id: '1002',
          time: '2024-03-04 14:20',
          photos: [
            { id: 1, url: '/static/mock/photo4.jpg' },
            { id: 2, url: '/static/mock/photo5.jpg' },
            { id: 3, url: '/static/mock/photo6.jpg' }
          ],
          composite: '/static/mock/composite2.jpg',
          gif: '/static/mock/gif2.gif'
        }
      ];
    },
    // 修改筛选方法，添加缓存清理
    filterTasks() {
      log('Filter Tasks', '筛选任务', {
        startDate: this.startDate,
        endDate: this.endDate
      });
      
      // 清除旧的缓存
      this.clearAllRelatedCaches();
      
      this.isInitialLoading = true;
      this.page = 1;
      this.hasMoreTasks = true;
      this.loadTasks();
      
      uni.showToast({
        title: `已筛选 ${this.startDate} 至 ${this.endDate} 的记录`,
        icon: 'none'
      });
    },
    async loadMore() {
      if (this.isLoadingMore || !this.hasMoreTasks) return;
      
      log('Load More', '加载更多数据', { nextPage: this.page + 1 });
      
      this.isLoadingMore = true;
      this.page++;
      await this.loadTasks();
    },
    goBack() {
      uni.navigateTo({
        url: '/pages/start/index'
      });
    },
    // 照片预览
    previewPhoto(photo) {
      // 强制使用原图URL进行预览
      let photoUrl = '';
      
      // 根据不同类型选择正确的原图URL
      if (photo.original_url) {
        // 如果明确提供了原图URL，始终优先使用
        photoUrl = photo.original_url;
      } else if (photo.type === 'original') {
        // 原始照片使用photo_url
        photoUrl = photo.photo_url;
      } else if (photo.type === 'gif') {
        // GIF使用gif_url
        photoUrl = photo.original_url || photo.gif_url;
      } else {
        // 合成照片使用image_url而非thumbnail_url
        photoUrl = photo.image_url;
      }
      
      log('Preview Photo', '预览高清原图', { photoUrl, photoType: photo.type });
      
      // 重置图片加载状态
      this.previewImageLoaded = false;
      
      // 设置预览信息
      this.previewImageUrl = photoUrl;
      
      // 如果传入了完整的任务信息，直接使用
      if (photo.task) {
        if (photo.type === 'original') {
          this.previewPhotoInfo = `任务 #${photo.task._id} - 照片 ${photo.index}`;
        } else if (photo.type === 'composite') {
          this.previewPhotoInfo = `任务 #${photo.task._id} - 合成照片`;
        } else if (photo.type === 'gif') {
          this.previewPhotoInfo = `任务 #${photo.task._id} - GIF动图`;
        }
        this.previewPhotoTime = new Date(photo.task.create_date).toLocaleString();
      } else {
        // 查找所属任务
        let taskInfo = '';
        let taskTime = '';
        
        for (const task of this.tasks) {
          // 检查是否是原始照片
          const originalPhoto = task.photos.find(p => 
            p.photo_url === this.previewImageUrl || 
            p.original_url === this.previewImageUrl
          );
          if (originalPhoto) {
            taskInfo = `任务 #${task._id} - 照片 ${originalPhoto.index}`;
            taskTime = new Date(task.create_date).toLocaleString();
            break;
          }
          
          // 检查是否是合成照片
          const resultImage = task.result_images.find(r => 
            r.image_url === this.previewImageUrl || 
            r.original_url === this.previewImageUrl
          );
          if (resultImage) {
            taskInfo = `任务 #${task._id} - 合成照片`;
            taskTime = new Date(task.create_date).toLocaleString();
            break;
          }
          
          // 检查是否是GIF
          if (task.gif_url === this.previewImageUrl) {
            taskInfo = `任务 #${task._id} - GIF动图`;
            taskTime = new Date(task.create_date).toLocaleString();
            break;
          }
        }
        
        this.previewPhotoInfo = taskInfo;
        this.previewPhotoTime = taskTime;
      }
      
      // 打开预览弹窗
      this.$refs.photoPreviewPopup.open();
    },
    closePhotoPreview() {
      this.$refs.photoPreviewPopup.close();
      // 重置图片加载状态
      this.previewImageLoaded = false;
    },
    // 分享照片
    async sharePhoto(photo) {
      log('Share Photo', '开始分享照片', {
        photoUrl: photo.photo_url || photo.image_url || photo.url,
        hasQrcode: !!photo.qrcode
      });

      try {
        // 如果已经有二维码，直接使用
        if (photo.qrcode) {
          uni.previewImage({
            urls: [photo.qrcode],
            current: 0
          });
          return;
        }
        
        // 否则生成分享链接
        const response = await uni.request({
          url: '/api/share/create',
          method: 'POST',
          data: {
            photoUrl: photo.photo_url || photo.image_url || photo.url
          }
        });
        
        if (response.statusCode !== 200) {
          throw new Error('生成分享链接失败');
        }
        
        const { shareUrl, qrCode } = response.data;
        
        // 显示分享弹窗
        uni.showModal({
          title: '分享照片',
          content: '请选择分享方式',
          showCancel: true,
          cancelText: '复制链接',
          confirmText: '扫码分享',
          success: (res) => {
            if (res.confirm) {
              // 显示二维码
              uni.previewImage({
                urls: [qrCode],
                current: 0
              });
            } else {
              // 复制链接
              uni.setClipboardData({
                data: shareUrl,
                success: () => {
                  uni.showToast({
                    title: '链接已复制到剪贴板',
                    icon: 'success'
                  });
                }
              });
            }
          }
        });

        log('Share Success', '照片分享成功', {
          shareUrl,
          qrCode
        });
      } catch (error) {
        log('Share Error', '分享失败', { error: error.message });
        console.error('分享失败:', error);
        uni.showToast({
          title: '分享失败，请重试',
          icon: 'none'
        });
      }
    },
    // 下载GIF
    downloadGif(gifUrl) {
      uni.showToast({
        title: 'GIF已下载到本地',
        icon: 'success'
      });
    },
    // 打印照片
    handlePrint(photo) {
      if (!photo || !photo.image_url) {
        uni.showToast({
          title: '没有可打印的照片',
          icon: 'none'
        });
        return;
      }
      
      // 直接开始打印，不再显示打印预览弹窗
      log('Print Start', '开始直接打印照片', { photoUrl: photo.image_url });
      
      try {
        // 显示加载状态
        uni.showLoading({
          title: '准备打印中...',
          mask: true
        });
        
        // 创建打印窗口
        const printWindow = window.open('', '_blank');
        if (!printWindow) {
          throw new Error('无法创建打印窗口，请检查浏览器是否允许弹出窗口');
        }
        
        // 写入打印内容
        const htmlContent = `
          <!DOCTYPE html>
          <html>
            <head>
              <title>打印照片</title>
              <style>
                @page { size: auto; margin: 0mm; }
                html, body { margin: 0; padding: 0; height: 100%; background-color: white; }
                .print-container { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; }
                img { max-width: 100%; max-height: 100%; object-fit: contain; }
              </style>
            </head>
            <body>
              <div class="print-container">
                <img src="${photo.image_url}" alt="打印照片" onload="setTimeout(function() { window.print(); window.close(); }, 500)">
              </div>
            </body>
          </html>
        `;
        
        printWindow.document.write(htmlContent);
        printWindow.document.close();
        
        // 打印完成后显示提示
        setTimeout(() => {
          uni.hideLoading();
          uni.showToast({
            title: '打印任务已发送',
            icon: 'success'
          });
        }, 1000);
        
      } catch (error) {
        uni.hideLoading();
        log('Print Error', '打印失败', { error: error.message });
        console.error('打印失败:', error);
        uni.showToast({
          title: error.message || '打印失败，请重试',
          icon: 'none'
        });
      }
    },
    // 删除任务
    showDeleteConfirm(task) {
      log('Delete Confirm', '显示删除确认框', { taskId: task._id });
      this.currentTask = task;
      this.$refs.deleteConfirmPopup.open();
    },
    async confirmDelete() {
      if (!this.currentTask) return;
      
      log('Delete Task', '开始删除任务', { taskId: this.currentTask._id });
      
      try {
        // 删除数据库记录
        await db.collection('a-tasks')
          .doc(this.currentTask._id)
          .remove();
        
        log('Delete Success', '任务删除成功', { taskId: this.currentTask._id });
        
        // 从缓存中移除已删除的任务
        const cachedData = this.getFromCache();
        if (cachedData) {
          cachedData.tasks = cachedData.tasks.filter(t => t._id !== this.currentTask._id);
          this.saveToCache(cachedData.tasks);
        }
        
        // 重置页面状态并重新加载
        this.page = 1;
        this.hasMoreTasks = true;
        this.isInitialLoading = true;
        await this.loadTasks();
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } catch (error) {
        log('Delete Error', '删除失败', {
          taskId: this.currentTask._id,
          error: error.message
        });
        console.error('删除失败:', error);
        uni.showToast({
          title: '删除失败，请重试',
          icon: 'none'
        });
      } finally {
        this.currentTask = null;
        this.$refs.deleteConfirmPopup.close();
      }
    },
    cancelDelete() {
      this.currentTask = null;
    },
    onPreviewImageLoad() {
      // 使用更可靠的方式添加loaded类来显示图片
      this.$nextTick(() => {
        // 设置一个标志来触发CSS过渡效果
        setTimeout(() => {
          this.previewImageLoaded = true;
        }, 100);
      });
    },
    async updatePrintStatus() {
      // 实现更新打印状态的逻辑
    }
  }
}
</script>

<style>
body {
  background-color: #f8f9fa;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  min-height: 100vh;
}

.app-container {
  width: 100%;
  min-height: 100vh;
}

.history-container {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border: 1.5px solid #dadce0;
  border-radius: 12px;
  color: #5f6368;
  font-size: 15px;
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.back-btn:active {
  background-color: #f1f3f4;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 8px 16px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.date-filter text {
  color: #5f6368;
  font-size: 15px;
  font-weight: 500;
  white-space: nowrap;
}

.date-picker {
  height: 42px;
  padding: 0 12px;
  border: 1.5px solid #dadce0;
  border-radius: 12px;
  color: #3c4043;
  font-size: 15px;
  background-color: #ffffff;
  transition: all 0.2s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.date-picker:focus {
  border-color: #1a73e8;
  box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.15);
  outline: none;
}

.btn.btn-primary.search-btn {
  height: 42px;
  padding: 0 22px;
  font-size: 15px;
  font-weight: 600;
  background-color: #1a73e8;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(26, 115, 232, 0.25);
  display: flex;
  align-items: center;
  gap: 8px;
  border: none;
  color: #ffffff !important;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.btn.btn-primary.search-btn * {
  color: #ffffff !important;
}

.search-btn-text {
  color: #ffffff !important;
  font-weight: 700;
  letter-spacing: 0.5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.btn.btn-primary.search-btn::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.btn.btn-primary.search-btn:active {
  background-color: #1557b0;
  box-shadow: 0 8px 20px rgba(26, 115, 232, 0.35);
  transform: translateY(-2px);
}

.btn.btn-primary.search-btn:active::after {
  opacity: 1;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.empty-title {
  font-size: 20px;
  color: #5f6368;
  margin: 16px 0 8px;
}

.empty-desc {
  font-size: 16px;
  color: #9aa0a6;
}

/* 任务卡片样式 */
.task-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  overflow: hidden;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #dadce0;
}

.task-title {
  font-size: 18px;
  font-weight: 600;
  color: #202124;
}

.task-time {
  font-size: 14px;
  color: #5f6368;
}

.task-content {
  padding: 20px;
}

.photos-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #202124;
}

.photos-grid {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.photo-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.photo-item:hover {
  transform: scale(1.02);
}

.photo-item:active {
  transform: scale(0.98);
}

.original-photo {
  width: 200px;
  height: 200px;
}

.template-photo {
  width: 300px;
  height: 200px;
}

.gif-photo {
  width: 200px;
  height: 200px;
}

.photo-item image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-number {
  position: absolute;
  top: 8px;
  left: 8px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 600;
  font-size: 14px;
}

.photo-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 8px;
  display: flex;
  justify-content: space-around;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.photo-item:active .photo-actions {
  opacity: 1;
}

.photo-action-btn {
  color: white;
  font-size: 16px;
  cursor: pointer;
  padding: 8px;
}

.task-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #dadce0;
}

.task-action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

.print-btn {
  background-color: #34a853;
  color: white;
}

.delete-btn {
  background-color: #ea4335;
  color: white;
}

.load-more {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.load-more-btn {
  padding: 12px 24px;
  background-color: white;
  border: 1px solid #dadce0;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #1a73e8;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.load-more-btn:active {
  background-color: #f8f9fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 预览模态框样式 */
.photo-preview-modal {
  position: relative;
  width: 90vw;
  max-width: 1200px;
  height: 90vh;
  display: flex;
  flex-direction: column;
  background: transparent;
}

.preview-close {
  position: absolute;
  top: -40px;
  right: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 100;
  transition: transform 0.2s ease;
}

.preview-close:hover {
  transform: rotate(90deg);
}

.preview-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border-radius: 16px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(20px);
  padding: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.preview-image.loaded {
  opacity: 1;
}

.preview-footer {
  margin-top: 16px;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
}

.preview-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-title {
  font-size: 18px;
  color: #ffffff;
  font-weight: 500;
}

.preview-time {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
}

/* 打印进度模态框样式 */
.print-icon-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.print-icon {
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.6;
    transform: scale(0.9);
  }
  50% {
    opacity: 1;
    transform: scale(1.1);
  }
  100% {
    opacity: 0.6;
    transform: scale(0.9);
  }
}

.progress-bar-container {
  width: 100%;
  height: 16px;
  background-color: #f1f3f4;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}

.progress-bar {
  height: 100%;
  background-color: #1a73e8;
  border-radius: 8px;
  transition: width 0.3s ease;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
}

.loading-text {
  font-size: 16px;
  color: #5f6368;
  margin-top: 16px;
}

/* 任务列表内容样式 */
.task-list-content {
  min-height: 200px;
}

/* 加载更多状态样式 */
.load-more-status {
  text-align: center;
  padding: 20px 0;
  color: #5f6368;
  font-size: 14px;
}

.load-more-text {
  color: #1a73e8;
}

.no-more-text {
  color: #9aa0a6;
}
</style>